@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="mb-3">
                <a href="{{ route('products.index') }}" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> 返回商品列表
                </a>
            </div>

            <div class="card">
                <div class="card-header">编辑商品</div>

                <div class="card-body">
                    <form action="{{ route('products.update', $product->id) }}" method="POST" enctype="multipart/form-data">
                        @csrf
                        @method('PUT')

                        <div class="mb-3">
                            <label for="name" class="form-label">商品名称</label>
                            <input type="text" 
                                   class="form-control @error('name') is-invalid @enderror" 
                                   id="name" 
                                   name="name" 
                                   value="{{ old('name', $product->name) }}" 
                                   required>
                            @error('name')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>

                        <div class="mb-3">
                            <label for="price" class="form-label">价格</label>
                            <input type="number" 
                                   class="form-control @error('price') is-invalid @enderror" 
                                   id="price" 
                                   name="price" 
                                   value="{{ old('price', $product->price) }}" 
                                   step="0.01" 
                                   required>
                            @error('price')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>

                        <div class="mb-3">
                            <label for="stock" class="form-label">库存</label>
                            <input type="number" 
                                   class="form-control" 
                                   id="stock" 
                                   value="{{ $product->stock }}" 
                                   readonly>
                            <small class="text-muted">库存信息仅供查看，不可直接修改。（操作进货、出库、退货、调拨、盘点等将自动更新库存）</small>
                        </div>

                        <div class="mb-3">
                            <label for="description" class="form-label">商品描述</label>
                            <textarea class="form-control @error('description') is-invalid @enderror" 
                                      id="description" 
                                      name="description" 
                                      rows="3">{{ old('description', $product->description) }}</textarea>
                            @error('description')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>

                        <!-- <div class="form-group">
                            <label for="product-image">商品主图（仅1张）</label>
                            <input type="file" id="product-image" class="form-control" name="image">
                            <div id="image-preview"></div>
                            <button type="button" id="upload-main-image" class="btn btn-primary mt-2">上传主图</button>
                        </div> -->

                        <button type="submit" class="btn btn-primary">保存修改</button>
                    </form>

                    <hr class="my-4">
                    
                    <form action="{{ route('products.toggle-sale', $product) }}" method="POST">
                        @csrf
                        @method('PATCH')
                        @if($errors->any())
                            <div class="alert alert-danger">
                                <ul>
                                    @foreach($errors->all() as $error)
                                        <li>{{ $error }}</li>
                                    @endforeach
                                </ul>
                            </div>
                        @endif
                        
                        <input type="hidden" name="debug" value="1">
                        
                        <button type="submit" 
                                class="btn {{ $product->status ? 'btn-danger' : 'btn-success' }}">
                            {{ $product->status ? '下架商品' : '上架商品' }}
                        </button>
                    </form>
                </div>
            </div>

            <hr class="my-4">

            <div class="card">
                <div class="card-header">商品图片（最多8张）</div>

                <div class="card-body">
                    <div id="upload-alert-box" class="alert" style="display: none;" role="alert"></div>
                    
                    <form id="uploadForm" 
                          class="mb-4" 
                          enctype="multipart/form-data" 
                          method="POST"
                          action="{{ route('media.store', $product) }}">
                        @csrf
                        <div class="mb-3">
                            <label for="image" class="form-label">上传图片</label>
                            <input type="file" 
                                   class="form-control" 
                                   id="image" 
                                   name="image" 
                                   accept="image/*"
                                   required>
                            <div class="form-text">请选择要上传的图片文件（JPG、PNG等）</div>
                        </div>
                        <div class="d-flex align-items-center">
                            <button type="submit" class="btn btn-primary">上传</button>
                            <span id="upload-alert-inline" class="ms-3" style="display: none;"></span>
                        </div>
                    </form>

                    <div id="imageGallery" class="row g-3">
                        @foreach($product->getMedia('product-images') as $media)
                            <div class="col-md-4 media-item" data-media-id="{{ $media->id }}">
                                <div class="card">
                                    <img src="{{ $media->getUrl() }}" 
                                         class="card-img-top" 
                                         alt="{{ $media->name }}">
                                    <div class="card-body">
                                        <button class="btn btn-danger btn-sm delete-media" 
                                                data-media-id="{{ $media->id }}">
                                            删除图片
                                        </button>
                                    </div>
                                </div>
                            </div>
                        @endforeach
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// 处理文件上传
document.addEventListener('DOMContentLoaded', function() {

    
    // 处理详图上传
    const uploadForm = document.getElementById('uploadForm');
    const uploadButton = uploadForm.querySelector('button[type="submit"]');
    const imageInput = document.getElementById('image');
    
    uploadForm.addEventListener('submit', function(e) {
        e.preventDefault();
        console.log('开始上传图片');
        
        // 检查图片数量是否已达上限
        const currentImageCount = document.querySelectorAll('.media-item').length;
        if (currentImageCount >= 8) {
            const alertBox = document.getElementById('upload-alert-box');
            alertBox.className = 'alert alert-warning';
            alertBox.style.display = 'block';
            alertBox.textContent = '商品图片已达8张上限，无法继续上传';
            return;
        }
        
        if (!imageInput.files || imageInput.files.length === 0) {
            alert('请先选择要上传的图片');
            return;
        }
        
        uploadButton.disabled = true;
        uploadButton.innerHTML = '上传中...';
        
        const formData = new FormData(this);
        const uploadUrl = this.getAttribute('action');
        
        console.log('上传URL:', uploadUrl);
        
        fetch(uploadUrl, {
            method: 'POST',
            body: formData,
            credentials: 'same-origin',
            headers: {
                'Accept': 'application/json'
            }
        })
        .then(response => {
            console.log('上传响应状态:', response.status);
            return response.text().then(text => {
                console.log('原始响应:', text);
                try {
                    if (!text) {
                        throw new Error('服务器返回空响应');
                    }
                    const data = JSON.parse(text);
                    if (!response.ok) {
                        throw new Error(data.error || '上传失败');
                    }
                    return data;
                } catch (e) {
                    console.error('解析响应失败:', e);
                    if (response.ok) {
                        window.location.reload();
                        return;
                    }
                    throw new Error('服务器响应格式错误');
                }
            });
        })
        .then(data => {
            if (!data) return;
            
            console.log('处理成功的数据:', data);
            const alertDiv = document.getElementById('upload-alert-inline');
            if (alertDiv) {
                alertDiv.className = 'text-success';
                alertDiv.style.display = 'inline';
                alertDiv.textContent = '图片上传成功';
                
                setTimeout(() => {
                    alertDiv.style.display = 'none';
                }, 5000);
            }
            
            const gallery = document.getElementById('imageGallery');
            const mediaHtml = `
                <div class="col-md-4 media-item" data-media-id="${data.media.id}">
                    <div class="card">
                        <img src="${data.media.original_url}" class="card-img-top" alt="${data.media.name}">
                        <div class="card-body">
                            <button class="btn btn-danger btn-sm delete-media" data-media-id="${data.media.id}">
                                删除图片
                            </button>
                        </div>
                    </div>
                </div>
            `;
            gallery.insertAdjacentHTML('beforeend', mediaHtml);
            
            uploadForm.reset();
        })
        .catch(error => {
            console.error('捕获到错误:', error);
            const alertDiv = document.getElementById('upload-alert-inline');
            if (alertDiv) {
                alertDiv.className = 'text-danger';
                alertDiv.style.display = 'inline';
                alertDiv.textContent = '上传失败，请重试';
                
                setTimeout(() => {
                    alertDiv.style.display = 'none';
                }, 5000);
            }
        })
        .finally(() => {
            uploadButton.disabled = false;
            uploadButton.innerHTML = '上传';
        });
    });
});

// 处理删除图片
document.addEventListener('click', function(e) {
    console.log('点击事件被触发');
    
    if (e.target.classList.contains('delete-media')) {
        console.log('点击了删除按钮');
        console.log('按钮数据:', e.target.dataset);
        
        const mediaId = e.target.dataset.mediaId;
        console.log('mediaId:', mediaId);
        
        if (confirm('确定要删除这张图片吗？')) {
            const deleteUrl = `{{ route('media.destroy', '') }}/${mediaId}`;
            console.log('删除URL:', deleteUrl);
            
            fetch(deleteUrl, {
                method: 'DELETE',
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                }
            })
            .then(response => {
                console.log('收到响应:', response.status);
                if (!response.ok) {
                    throw new Error('删除失败');
                }
                return response.json();
            })
            .then(data => {
                console.log('删除成功:', data);
                const mediaItem = document.querySelector(`.media-item[data-media-id="${mediaId}"]`);
                if (mediaItem) {
                    mediaItem.remove();
                    alert(data.message || '图片删除成功');
                }
            })
            .catch(error => {
                console.error('删除失败:', error);
                alert('删除失败，请重试');
            });
        }
    }
});
</script>

@endsection